package com.zhengqing.demo.common;

import com.zhengqing.demo.entity.CreateTableSql;
import com.zhengqing.demo.mapper.CommonMapper;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;

/**
 * 分表工具
 * @param
 */
@Component
public  class ShardingAlgorithmTool {

    @Autowired
    private  CommonMapper commonMapper;

    private static final HashSet<String> tableNameCache = new HashSet<>();

    public String shardingTablesCheckAndCreatAndReturn(String logicTableName, String resultTableName) {
        synchronized (logicTableName.intern()) {
            // 缓存中有此表 返回
            if (shardingTablesExistsCheck(resultTableName)) {
                return resultTableName;
            }
            // 缓存中无此表 建表 并添加缓存
            String sql = TableConstant.CREATE_TABLE_USER;
            sql = sql.replace(logicTableName, resultTableName);
            commonMapper.executeSql(sql);
            tableNameCache.add(resultTableName);
        }
        return resultTableName;
    }

    /**
     * 判断表是否存在于缓存中
     *
     * @param resultTableName 表名
     * @return 是否存在于缓存中
     */
    public boolean shardingTablesExistsCheck(String resultTableName) {
        return tableNameCache.contains(resultTableName);
    }

}
